package com.nike.amoeba.ui.frg

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.LogUtils
import com.kingja.loadsir.core.LoadService
import com.nike.amoeba.adapter.DownloadAdapter
import com.nike.amoeba.base.BaseFragment
import com.nike.amoeba.bean.db.AssetBean
import com.nike.amoeba.bean.db.MainDrawerBean
import com.nike.amoeba.bean.db.TaskStockListBean
import com.nike.amoeba.databinding.BNotTitleRecyclerBinding
import com.nike.amoeba.ext.init
import com.nike.amoeba.ext.loadListData
import com.nike.amoeba.ext.loadServiceInit
import com.nike.amoeba.ext.setNbOnItemClickListener
import com.nike.amoeba.ext.showLoading
import com.nike.amoeba.mar.eventViewModel
import com.nike.amoeba.viewmodel.DownloadModel
import com.nike.amoeba.weight.recyclerview.SpaceItemDecoration
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import io.reactivex.rxjava3.subjects.BehaviorSubject
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import java.text.NumberFormat
import java.util.concurrent.TimeUnit


/**
 * @Author nike
 * @Date 2023/7/7 16:51
 * @Description  二期模组下载
 */
class DownloadFrg2 : BaseFragment<DownloadModel, BNotTitleRecyclerBinding>() {

    lateinit var loadsir: LoadService<Any>

    val adapter: DownloadAdapter by lazy { DownloadAdapter(arrayListOf()) }

    var disposable: Disposable? = null

    val numberFormat = NumberFormat.getInstance()

    // 创建一个 BehaviorSubject 来存储和发出数据列表
    lateinit var dataSubject: BehaviorSubject<List<AssetBean>>

    var compositeDisposable = CompositeDisposable()

    var mIndex = 0

    var mPeriod: Long = 1//每秒间隔

    override fun initView(savedInstanceState: Bundle?) {
        //状态页配置
        loadsir = loadServiceInit(mDatabind.swipeRefresh) {
            //点击重试时触发的操作
            loadsir.showLoading()
            mViewModel.onModuleList()
        }
        mDatabind.swipeRefresh.isEnabled = false
        //初始化recyclerView
        mDatabind.recyclerView.init(LinearLayoutManager(context), adapter).let {
            it.addItemDecoration(SpaceItemDecoration(ConvertUtils.dp2px(20f), ConvertUtils.dp2px(20f), true))
        }
        adapter.run {
            setNbOnItemClickListener{adapter, view, position ->

            }
        }

        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onPause(owner: LifecycleOwner) {
                super.onPause(owner)
                compositeDisposable?.dispose()
            }

            override fun onResume(owner: LifecycleOwner) {
                super.onResume(owner)
                mViewModel.viewModelScope.launch(Dispatchers.IO) {
                    mViewModel.mainDrawerDao.deleteAll()
//                    mViewModel.mainDrawerParentDao.deleteAll()

                    mViewModel.taskAssetDao.deleteAll()
                    mViewModel.assetDao.deleteAll()

                    mViewModel.taskStockListDao.deleteAll()
                    mViewModel.taskStockDao.deleteAll()

                    mViewModel.stockListDao.deleteAll()
                    mViewModel.stockEpcDao.deleteAll()

                    mViewModel.uploadOrderDao.deleteAll()
                    mViewModel.uploadOrderListDao.deleteAll()
                }
                if (adapter != null){
                    adapter.data.clear()
                }
//                mViewModel.onModuleList()
                mViewModel.onModuleList2()
            }
        })
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.listBean.observe(viewLifecycleOwner, Observer {
            loadListData(it, adapter, loadsir, mDatabind.recyclerView, mDatabind.swipeRefresh, it.pageSize)
            eventViewModel.mainDrawerUploadEvent.value = true
            if (it.listData.size != 0){
                mIndex = 0
                onIndexAdapter(mIndex)
            }
        })

        mViewModel.listStockBean2.observe(viewLifecycleOwner, Observer { bean ->
            val dataSubject: BehaviorSubject<List<TaskStockListBean>> = BehaviorSubject.createDefault(emptyList())
            compositeDisposable = CompositeDisposable()
            mViewModel.taskStockListDao.findAll(mViewModel.userId!!, mViewModel.companyId!!, bean.Code!!)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ list ->
                    dataSubject?.onNext(list)
                }, { throwable ->
                    LogUtils.e("MainActivity", "Error fetching data", throwable)
                })
                .let { compositeDisposable?.add(it) }
            // 每隔2秒从 BehaviorSubject 获取数据并打印列表的大小
            Observable.interval(mPeriod, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    dataSubject?.value?.let { list ->
                        LogUtils.d("MainActivity", "List size: ${list.size}")
                        val drawerBean = adapter.data[mIndex]
                        drawerBean.progress = list.size.toFloat()
                        adapter.setData(mIndex, drawerBean)
                        if (list.size == bean.TotalNum) {
                            compositeDisposable?.dispose()
                            mIndex += 1
                            onIndexAdapter(mIndex)
                        }
                    }
                }, { throwable ->
                    LogUtils.e("MainActivity", "Error in interval observable", throwable)
                })
                .let { compositeDisposable?.add(it) }

        })

        mViewModel.listAssetBean2.observe(viewLifecycleOwner, Observer {bean ->
            dataSubject = BehaviorSubject.create()
            compositeDisposable = CompositeDisposable()
            mViewModel.assetDao.findAll(mViewModel.userId!!, mViewModel.companyId!!, bean.Code!!)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ list ->
                    dataSubject?.onNext(list)
                }, { throwable ->
                    LogUtils.e("MainActivity", "Error fetching data", throwable)
                })
                .let { compositeDisposable?.add(it) }
            // 每隔2秒从 BehaviorSubject 获取数据并打印列表的大小
            Observable.interval(mPeriod, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    dataSubject?.value?.let { list ->
                        LogUtils.d("MainActivity", "List size: ${list.size}")
                        val drawerBean = adapter.data[mIndex]
                        drawerBean.progress = list.size.toFloat()
                        adapter.setData(mIndex, drawerBean)
                        if (list.size == bean.TotalNum) {
                            compositeDisposable?.dispose()
                            mIndex += 1
                            onIndexAdapter(mIndex)
                        }
                    }
                }, { throwable ->
                    // 添加 onError 回调
                    LogUtils.e("MainActivity", "Error in interval observable", throwable)
                })
                .let { compositeDisposable?.add(it) }
        })
    }

    fun onIndexAdapter(index: Int){
        if (index < adapter.data.size){
            val bean = adapter.data[index]
            val code = bean.Code
            val total = bean.Total
            if (bean.Type == 0){
                mViewModel.onStockTakeListRequest2(code, total)
            }else{
                mViewModel.onStockListRequest2(code, total)
            }
        }
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        //设置界面 加载中
//        loadsir.showLoading()
    }

}